# -*- coding: utf-8 -*-
from modules import parse

import urllib
import os
import string
import random
import re
import threading
import json
from sys import stdout

debugstring=""

class DownloadStarter():

	def __init__(self,url,quality="hd1080"):

		playlistBaseUrl = "https://gdata.youtube.com/feeds/api/playlists/%s?alt=json&start-index=1&max-results=50"
		
		pattern=re.compile('(?:\?|&)v=([^&]*)')
		isvideo=pattern.findall(url)
		
		if isvideo:
			YoutubeDownloader(url,quality="small").start()

		else:
			playlistId = re.findall('(?:?|&)list=([^&]*)',url)
			if (len(playlistId) == 1):
				playlistId = playlistId[0]
				playlistData=open(urllib.urlretrieve(playlistBaseUrl % playlistId)[0]).read()
				playlistData=json.loads(playlistData)

			
				pllength=int(playlistData['feed']['openSearch$totalResults']['$t'])
				howmanyrequests=pllength//50+1

				for x in range(1,howmanyrequests+1):
					for entry in playlistData['feed']['entry']:
						sanitizedUrl = re.sub('&feature=youtube_gdata_player','',entry['media$group']['media$player'][0]['url'])

						videoName = entry['title']['$t']
						videoName = re.sub(r"[\\/:*?\"<>|]","",videoName)
						YoutubeDownloader(sanitizedUrl,"./debug/"+videoName+".flv",quality="small").start()

					playlistBaseUrl="https://gdata.youtube.com/feeds/api/playlists/%s?alt=json&start-index="+str(50*x+1)+"&max-results=50"
					playlistData=open(urllib.urlretrieve(playlistBaseUrl % playlistId)[0]).read()
					playlistData=json.loads(playlistData)
			else:
				print("The url could not be parsed")
			




class YoutubeDownloader(threading.Thread):

	qualities=["hd1080","hd720","large","medium","small"]
	
	def __init__(self,url,filepath=False,quality="hd1080"):
		threading.Thread.__init__(self)

		self.url = url
		self.filepath = filepath
		self.quality = quality

	def run(self):
		print("starting "+self.url)
		self.downloadYoutube()
		print("finished "+self.url)


	def downloadYoutube(self):
		self.video = parse.Video(self.url)
		map_dict = self.video.map_dict

		if not self.quality:
			self.quality=self.qualities[0]

		testquality=self.qualities.index(self.quality)

		while not map_dict.has_key(self.qualities[testquality]):
			testquality+=1
			
		self.quality=self.qualities[testquality]

		map_quality_dict=map_dict[self.quality]

		def print_inline(msg):
			stdout.write("\r%s" % msg)
			stdout.flush()
		def dlProgress(count,blockSize,totalSize):
			percent=int(count*blockSize*50/totalSize)
			print_inline("["+"-"*percent+" "*(50-percent)+"]")


		directurl=map_quality_dict['url']
		try:
			signature=map_quality_dict['sig']
		except KeyError, e:
			signature=map_quality_dict['s']
		urllib.urlretrieve(directurl+"&signature="+signature,self.filepath,reporthook=dlProgress)


f=open(r"./debug/file_1","w")
f.write(str(debugstring))
f.close()